import {useEffect, useImperativeHandle, useState} from 'react';
import type {RadioChangeEvent} from 'antd';
import {DatePicker, Form, Radio, Select} from 'antd';
import {getHolidays, getLastHoliday} from '@/services/db/public';
import {useRequest} from 'ahooks';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

const {useForm} = Form;
const {Option} = Select;
const DateQuery: React.FC<{
  dateQueryRef?: any;
  options?: { label: string, value: 'year' | 'month' | 'day' | 'holiday' | 'quarter' }[],
  initialValues?: {
    scope: 'year' | 'month' | 'day' | 'holiday' | 'quarter' | 'all' | 'current',
    date: dayjs.Dayjs,
    holiday?: string
  },
  onSubmit?: (params: any) => void
}> = (props) => {
  const [form] = useForm();

  const {
    options = [
      {label: '月度', value: 'month'},
      {label: '年度', value: 'year'},
    ],
    initialValues = {scope: 'year', date: dayjs(new Date())},
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onSubmit = (params: any) => {
      return params
    }
  } = props;

  const [radioValue, setRadioValue] = useState<any>(initialValues.scope || 'year')

  const scopeToPicker: any = {
    year: 'year',
    month: 'month',
    quarter: 'quarter',
    holiday: 'year',
    day: 'date',
  };

  const onChangeRadio = (e: RadioChangeEvent) => {
    const value = e.target.value;
    setRadioValue(value)
    if (value === 'holiday') {
      const data = form.getFieldValue('date');
      holidayListRun({
        year: dayjs(data).format('YYYY'),
      });
    }
    if (value === 'current') {
      form.setFieldsValue({
        date: dayjs(),
      });
    }
    if (value === 'all') {
      form.setFieldsValue({
        date: null,
      });
    }
  };

  const onChangeHoliday = (value: any) => {
    if (value) {
      handleSubmit();
    }
  };

  const {
    run: lastHolidayRun,
  } = useRequest(getLastHoliday, {
    manual: true,
    onSuccess(res) {
      const formYear = form.getFieldValue('date').format('YYYY');
      const currentYear = dayjs().format('YYYY');
      if (formYear === currentYear) {
        form.setFieldsValue({
          holiday: res.data.holiday,
        });
        handleSubmit();
      }
    },
  });

  const {data: holidayList, run: holidayListRun}: any = useRequest(getHolidays, {
    manual: true,
    onSuccess(res) {
      if (!res.data?.length) {
        return false;
      }
      const formYear = form.getFieldValue('date').format('YYYY');
      const currentYear = dayjs().format('YYYY');
      if (formYear === currentYear) {
        lastHolidayRun();
      } else {
        form.setFieldsValue({
          holiday: res.data[0].holiday,
        });
        handleSubmit();
      }
    },
  });
  const handleSubmit = (values?: any) => {
    if (!values) {
      values = form.getFieldsValue();
    }
    let dateStr = formatDate(values.date)
    if (form.getFieldValue('scope') === 'holiday') {
      dateStr += "-" + values.holiday
    }
    onSubmit({...values, dateStr});
  };

  const formatDate = (date: dayjs.Dayjs) => {
    if (!date) return '';
    let format = 'YYYY';
    switch (form.getFieldValue('scope')) {
      case 'month':
        format = "YYYY-MM";
        break
      case 'quarter':
        format = "YYYY-Q";
        break
      case 'day':
        format = "YYYY-MM-DD";
        break
      default:
    }
    return date.format(format);
  }

  const onValuesChange = (_: any, allValues: any) => {
    if (!allValues.date) {
      return false;
    }
    if (allValues.scope == 'holiday') {
      return false;
    }
    handleSubmit(allValues);
  };

  useEffect(() => {
    handleSubmit(initialValues)
  }, []);
  useImperativeHandle(props.dateQueryRef, () => {
    return {
      setFormDate(values: any) {
        form.setFieldsValue(values);
      },
      changeType(){
        const value = form.getFieldValue('scope');
        setRadioValue(value)
        if (value === 'holiday') {
          const data = form.getFieldValue('date');
          holidayListRun({
            year: dayjs(data).format('YYYY'),
          });
        }
        if (value === 'current') {
          form.setFieldsValue({
            date: dayjs(),
          });
        }
        if (value === 'all') {
          form.setFieldsValue({
            date: null,
          });
        }
      }
    }

  }, [])
  return (
    <Form layout="inline" prefixCls='dp-form' form={form} initialValues={initialValues}
          onValuesChange={onValuesChange}>
      <Form.Item prefixCls='dp-form' name="scope">
        <Radio.Group prefixCls='dp-radio' onChange={onChangeRadio} buttonStyle="solid">
          {options?.map((item: any, index: number) => {
            return (
              <Radio.Button prefixCls='dp-radio' value={item.value} key={index}>
                {item.label}
              </Radio.Button>
            );
          })}
        </Radio.Group>
      </Form.Item>
      <Form.Item prefixCls='dp-form' name="date">
        <DatePicker
          prefixCls='dp-picker'
          locale={locale}
          picker={scopeToPicker[radioValue] || 'date'}
          disabled={form.getFieldValue('scope') === 'current' || form.getFieldValue('scope') === 'all'}
          onChange={() => {
            if (form.getFieldValue('scope') === 'holiday') {
              const data = form.getFieldValue('date');
              holidayListRun({
                year: dayjs(data).format('YYYY'),
              });
            }
          }}
        />
      </Form.Item>
      {form.getFieldValue('scope') === 'holiday' && (
        <Form.Item prefixCls='dp-form' name="holiday" dependencies={['scope']}>
          <Select
            prefixCls='dp-select'
            placeholder="请选择节假日"
            onChange={onChangeHoliday}
          >
            {holidayList?.map((item: any) => (
              <Option key={item.id} value={item.holiday}>
                {item.holiday}
              </Option>
            ))}
          </Select>
        </Form.Item>
      )}
    </Form>
  );
};
export default DateQuery;
